package com.example.drink_order_system.fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.drink_order_system.R;
import com.example.drink_order_system.activity.MainActivity;
import com.example.drink_order_system.adapter.OrderAdapter;
import com.example.drink_order_system.entity.Ordered_drinks;
import com.example.drink_order_system.entity.discount_quan;

import java.util.ArrayList;

import DataBase.UserDbHelper;

public class ShopFragment extends Fragment {
    private RecyclerView bill_listView;
    private LinearLayoutManager llM;

    private LayoutInflater layoutInflater;
    private Context mContext;
    private TextView TV_cost;
    private EditText ET_people;
    private EditText ET_table;
    private CheckBox CB_takeAway;
    private ImageButton BT_delete;
    private Button BT_buy;
    private int drinkCost;
    private float serviceCost;
    private double total_cost;

    private AlertDialog buyDialog = null;
    private AlertDialog askDialog = null;
    private AlertDialog chooseDialog = null;
    private AlertDialog.Builder builder = null;
    private View view_buy;
    private View view_ask;
    private View view_discount;
    private View view;
    private String userName;
    public ShopFragment() {
        // Required empty public constructor
    }
    public static ShopFragment newInstance(String userName) {
        ShopFragment myFragment = new ShopFragment();
        Bundle args = new Bundle();
        args.putString("userName", userName);
        myFragment.setArguments(args);
        return myFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userName = getArguments().getString("userName");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getActivity();
        layoutInflater = inflater;
        view = inflater.inflate(R.layout.fragment_shop, container, false);
        bill_listView = (RecyclerView) view.findViewById(R.id.RV_bill);
        llM = new LinearLayoutManager(this.getActivity());
        bill_listView.setLayoutManager(llM);
        OrderAdapter orderAdapter = new OrderAdapter(inflater, Ordered_drinks.getOrdered_array());
        orderAdapter.buttonSetOnClick((new OrderAdapter.MyClickListener() {
            @Override
            public void onAddClick(View v, int position) {
                Ordered_drinks.addDrink(position);
                refresh();
            }

            public void onSubClick(View v, int position){
                Ordered_drinks.subtractDrink(position);
                refresh();
            }
        }));
        bill_listView.setAdapter(orderAdapter);
        TV_cost = view.findViewById(R.id.textView_cost);
        ET_people = view.findViewById(R.id.editText_people);
        ET_table = view.findViewById(R.id.editText_table);
        CB_takeAway = view.findViewById(R.id.checkBox);
        BT_delete = view.findViewById(R.id.button_delete);
        BT_buy = view.findViewById(R.id.button_buy);
        drinkCost = Ordered_drinks.getDrinkCost();
        serviceCost = 0.2f;
        if(!ET_people.getText().equals(""))
        {
            serviceCost = 0.2f*Integer.parseInt((String.valueOf(ET_people.getText())));
        }
        TV_cost.setText(String.format("饮料费：￥ %d \n服务费：￥ %.1f", drinkCost, serviceCost));
        ET_people.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals(""))
                {
                    s.append("1");
                }
                if(s.toString().equals("0"))
                {
                    s.replace(0, 1, "1");
                }
                serviceCost = 0.2f;
                if(!ET_people.getText().equals(""))
                {
                    serviceCost = 0.2f*Integer.parseInt((String.valueOf(ET_people.getText())));
                }
                TV_cost.setText(String.format("饮料费：￥ %d \n服务费：￥ %.1f", drinkCost, serviceCost));
            }
        });

        ET_people.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals(""))
                {
                    s.append("1");
                }
                if(s.toString().equals("0"))
                {
                    s.replace(0, 1, "1");
                }
                serviceCost = 0.2f;
                if(!ET_people.getText().equals(""))
                {
                    serviceCost = 0.2f*Integer.parseInt((String.valueOf(ET_people.getText())));
                }
                TV_cost.setText(String.format("饮料费：￥ %d \n服务费：￥ %.1f", drinkCost, serviceCost));
            }
        });

        ET_table.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals(""))
                {
                    s.append("1");
                }
                if(Integer.valueOf(s.toString())<=0)
                {
                    s.replace(0, 1, "1");
                }
                if(Integer.valueOf(s.toString())>30)
                {
                    s.replace(0, s.length(), "30");
                }
            }
        });

        BT_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "您已清空购物车！", Toast.LENGTH_SHORT).show();
                Ordered_drinks.clearOrdered_array();
                refresh();
            }
        });

        builder = new AlertDialog.Builder(this.getActivity());

        view_ask = inflater.inflate(R.layout.ask_if_use_discount,null,false);
        builder.setView(view_ask);
        builder.setCancelable(false);
        askDialog = builder.create();
        view_ask.findViewById(R.id.use_dis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                askDialog.dismiss();
                chooseDialog.show();
            }
        });
        view_ask.findViewById(R.id.not_use_dis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                askDialog.dismiss();
                buyDialog.show();
                if(view_buy!=null) {
                    TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                    {
                        total_cost = drinkCost+serviceCost;
                        TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                ,drinkCost, serviceCost, total_cost));
                    }
                }
            }
        });

        view_discount = inflater.inflate(R.layout.choose_discount_page,null,false);
        builder.setView(view_discount);
        builder.setCancelable(false);
        chooseDialog = builder.create();
        choose_my_discount_list_adapter myAdapter_choose = new choose_my_discount_list_adapter();
        ListView choose_list = view_discount.findViewById(R.id.choose_discount_list);
        choose_list.setAdapter(myAdapter_choose);
        view_discount.findViewById(R.id.choose_not_use_dis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseDialog.dismiss();
                buyDialog.show();
                if(view_buy!=null) {
                    TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                    {
                        total_cost = drinkCost+serviceCost;
                        TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                ,drinkCost, serviceCost, total_cost));
                    }
                }
            }
        });


        view_buy = inflater.inflate(R.layout.dialogue_buy, null, false);
        builder.setView(view_buy);
        builder.setCancelable(false);
        buyDialog = builder.create();
        view_buy.findViewById(R.id.button_quit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buyDialog.dismiss();
            }
        }
        );

        view_buy.findViewById(R.id.button_bought).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Account temp = new Account(userName, mContext);
                String takeAway = "0";
                if(CB_takeAway.isChecked())
                {
                    takeAway = "1";
                }
                String cost = String.format("%.1f",total_cost);
                MainActivity.now_user.saveBill(takeAway, cost);
                Ordered_drinks.clearOrdered_array();
                refresh();
                buyDialog.dismiss();
            }
        }
        );






        BT_buy.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v){
                if(drinkCost==0)
                {
                    Toast.makeText(getContext(), "请先选购饮品再结账！", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    askDialog.show();
                }
            }
        });
        return view;
    }



    private void refresh() {
        OrderAdapter orderAdapter = new OrderAdapter(layoutInflater, Ordered_drinks.getOrdered_array());
        orderAdapter.buttonSetOnClick((new OrderAdapter.MyClickListener() {
            @Override
            public void onAddClick(View v, int position) {
                Ordered_drinks.addDrink(position);
                refresh();
            }

            public void onSubClick(View v, int position){
                Ordered_drinks.subtractDrink(position);
                refresh();
            }
        }));
        bill_listView.setAdapter(orderAdapter);
        drinkCost = Ordered_drinks.getDrinkCost();
        serviceCost = 0.2f;
        ET_people.setText("1");
        if(!ET_people.getText().equals(""))
        {
            serviceCost = 0.2f*Integer.parseInt((String.valueOf(ET_people.getText())));
        }
        TV_cost.setText(String.format("饮料费：￥ %d \n服务费：￥ %.1f", drinkCost, serviceCost));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        refresh();
    }



    class choose_my_discount_list_adapter extends BaseAdapter {
        private ArrayList<discount_quan> discountQuans;
        private TextView show_detail;
        private TextView start_time;
        private TextView end_time;
        private AppCompatButton go_use;
        public choose_my_discount_list_adapter(){
            super();
            discountQuans = discount_quan.getDiscountQuans();
        }
        @Override
        public int getCount() {
            return discountQuans.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = View.inflate(getContext(),R.layout.choose_discount_item_layout,null);
            show_detail = view.findViewById(R.id.choose_discount_detail_text);
            start_time = view.findViewById(R.id.choose_discount_start_time);
            end_time = view.findViewById(R.id.choose_discount_end_time);
            if (discountQuans.size()<=0){
                Toast.makeText(getContext(),"暂时没有优惠券！",Toast.LENGTH_SHORT).show();
            }else {
                show_detail.setText(discountQuans.get(i).getDetail());
                start_time.setText("有效起始时间："+discountQuans.get(i).getStart_date());
                end_time.setText("失效截止时间："+discountQuans.get(i).getEnd_date());
            }
            go_use = view.findViewById(R.id.choose_go_to_use);
            go_use.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (discountQuans.get(i).getScore()){
                        case 500:
                            if (drinkCost+serviceCost>1){
                                total_cost = drinkCost+serviceCost-1;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                            ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 1000:
                            if (drinkCost+serviceCost>2){
                                total_cost = drinkCost+serviceCost-2;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 1500:
                            if (drinkCost+serviceCost>2.5){
                                total_cost = drinkCost+serviceCost-2.5;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 2000:
                            if (drinkCost+serviceCost>3){
                                total_cost = drinkCost+serviceCost-3;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 2500:
                            if (drinkCost+serviceCost>4){
                                total_cost = drinkCost+serviceCost-4;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 3000:
                            if (drinkCost+serviceCost>5){
                                total_cost = drinkCost+serviceCost-5;
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            Toast.makeText(getContext(), "使用成功！", Toast.LENGTH_SHORT).show();
                            break;
                        case 5000:
                            if (drinkCost+serviceCost>20){
                                total_cost = drinkCost+serviceCost;
                                Toast.makeText(getContext(), "该单交易大于20元，不符合条件！", Toast.LENGTH_SHORT).show();
                            }else {
                                total_cost = 0;
                            }
                            chooseDialog.dismiss();
                            buyDialog.show();
                            if(view_buy!=null) {
                                TextView TV_allCost = view_buy.findViewById(R.id.textView_allCost);
                                TV_allCost.setText(String.format("饮料费：￥ %d\n服务费：￥ %.1f\n总价：￥ %.1f\n请扫描以下二维码进行支付。"
                                        ,drinkCost, serviceCost, total_cost));
                            }
                            break;
                        default:
                            break;
                    }
                    if (total_cost==drinkCost+serviceCost){

                    }else {
                        UserDbHelper db = (UserDbHelper) UserDbHelper.getSqliteHelper(getContext());
                        db.delete_discount(discountQuans.get(i).getTag());
                        discountQuans.remove(i);
                    }
                }
            });
            return view;
        }
    }
}